package com.ptu.spzx.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.manager.mapper.SysDeptMapper;
import com.ptu.spzx.manager.service.DeptService;
import com.ptu.spzx.manager.utils.DeptHelper;
import com.ptu.spzx.model.entity.system.SysDept;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.model.vo.system.SysDeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements DeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Override
    public void removeById(Long id) {
        //根据当前的菜单id来查询是否包含子菜单
        int count=sysDeptMapper.selectCountById(id);
        //判断，count大于0，包含子菜单
        if(count>0){
            throw  new ptuException(ResultCodeEnum.NODE_ERROR);
        }
        //count等于0，直接删除
        sysDeptMapper.deleteDept(id);
    }

    @Override
    public void updateDept(SysDept sysDept) {
        sysDeptMapper.updateDept(sysDept);
    }

    @Override
    public void saveDept(SysDept sysDept) {
        String deptName = sysDept.getDeptName();
        System.out.println(deptName);
        SysDept sysDept1 = sysDeptMapper.selectDeptsByName(deptName);
        if(!StringUtils.isEmpty(sysDept1)){
            throw new ptuException (ResultCodeEnum.DATA_EXIST);
        }
        System.out.println("=========================================");
        sysDeptMapper.saveDept(sysDept);
    }

    @Override
    public List<SysDeptVo> findNodes() {
        List<SysDept> sysDepts = sysDeptMapper.selectAll();
        //根据userId查询出可以操作的菜单
        //封装要求的数据格式，返回
        List<SysDept> sysDeptList = DeptHelper.buildTree(sysDepts);
        List<SysDeptVo> sysDeptVos = this.buildDepts(sysDeptList);

        return sysDeptVos;
    }

    @Override
    public List<SysDept> findDeptAll() {
       return sysDeptMapper.selectAll();
    }

    @Override
    public List<SysDeptVo> findDept(String keyWord) {
        if(!StringUtils.hasText(keyWord)){
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
        List<SysDeptVo> sysDeptVos=null;
        List<SysDept> sysDeptsAll=new ArrayList<>();
        List<SysDept> sysDepts1=new ArrayList<>();
        List<SysDept> sysDepts3=new ArrayList<>();
        SysDept sysDept = sysDeptMapper.selectDeptsByName(keyWord);
        List<Long> parentIds=new ArrayList<>();
            Long parentId = sysDept.getParentId();
            Integer deptLevel = sysDept.getDeptLevel();
//            parentIds.add(parentId);
//            level.add(deptLevel);
//        List<Long> distinctParents = parentIds.stream().distinct().collect(Collectors.toList());
//        System.out.println(distinctParents);
        //如果是莆田学院
        if(parentId==0){
            List<SysDept> sysDeptsBig = sysDeptMapper.selectAll();
            //根据userId查询出可以操作的菜单
            //封装要求的数据格式，返回
            sysDeptsAll.addAll(sysDeptsBig);
        }else if(deptLevel==1){
            //第二次寻找
                SysDept sysDepts2 = sysDeptMapper.selectParentId(parentId);
                sysDepts1.add(sysDepts2); //最大的部门
                sysDepts1.add(sysDept);
                //向下寻找
                List<SysDept> sysDepts4 = sysDeptMapper.selectSonId(sysDept.getId());
                List<SysDept> sysDepts5=new ArrayList<>();
                if(sysDepts4.size()!=0){
                    for(SysDept sysDept6:sysDepts4){ //3
                        sysDepts5 = sysDeptMapper.selectSonId(sysDept6.getId());
                    }
                }
                sysDeptsAll.addAll(sysDepts1);
                if(sysDepts4.size()!=0){
                    sysDeptsAll.addAll(sysDepts4);
                }
            if(!sysDepts5.isEmpty()||sysDepts5.size()!=0){
                    sysDeptsAll.addAll(sysDepts5);
                }
        } else if (deptLevel==2) {
            //2级寻找1
                SysDept sysDepts2 = sysDeptMapper.selectParentId(parentId);
                sysDepts1.add(sysDepts2);
                sysDepts1.add(sysDept);
                parentIds.clear();
                Long parent = sysDepts2.getParentId();
                SysDept sysDepts7 = sysDeptMapper.selectParentId(parent);
                sysDepts3.add(sysDepts7);
            //向下寻找
            List<SysDept> sysDepts5 = sysDeptMapper.selectSonId(sysDept.getId());
            sysDeptsAll.addAll(sysDepts3);
            sysDeptsAll.addAll(sysDepts1);
            if(sysDepts5.size()!=0){
                sysDeptsAll.addAll(sysDepts5);
            }
        } else{
            //第二次寻找 2
                SysDept sysDepts2 = sysDeptMapper.selectParentId(parentId);
                sysDepts1.add(sysDepts2);
                sysDepts1.add(sysDept);
            System.out.println(sysDepts1);
            //第二级部门 1
                parentIds.clear();
                Long parentId3 = sysDepts2.getParentId();
            //第三次寻找
                SysDept sysDepts9 = sysDeptMapper.selectParentId(parentId3);
                sysDepts3.add(sysDepts9);
            //第三级部门
                Long parentId10 = sysDepts9.getParentId();
            //第三次寻找
                List<SysDept> sysDepts5=new ArrayList<>();
                SysDept sysDepts11 = sysDeptMapper.selectParentId(parentId10);
                sysDepts5.add(sysDepts11);
            sysDeptsAll.addAll(sysDepts5);
            sysDeptsAll.addAll(sysDepts3);
            sysDeptsAll.addAll(sysDepts1);
        }
        List<SysDept> sysDeptList = DeptHelper.buildTree(sysDeptsAll);
        sysDeptVos = this.buildDepts(sysDeptList);
        return sysDeptVos;
    }

    @Override
    public Result findDeptId(Long id) {
        if(id==null){
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
       SysDept sysDept=sysDeptMapper.selectDeptId(id);
        if (sysDept==null){
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        return Result.build(sysDept,ResultCodeEnum.SUCCESS);
    }

    @Override
    public SysDept findDeptFeign(Long id) {
        SysDept sysDept = sysDeptMapper.selectDeptId(id);
        if(sysDept==null){
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        return sysDept;
    }

    @Override
    public PageInfo<SysDept> findByPage(Integer pageNum, Integer pageSize, String keyWord, List<Long> classIds) {
        LambdaQueryWrapper<SysDept> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SysDept::getId,SysDept::getDeptLevel,SysDept::getDeptName,SysDept::getDescription,SysDept::getStatus);
        lambdaQueryWrapper.eq(SysDept::getDeptLevel,3);
        lambdaQueryWrapper.like(keyWord!=null,SysDept::getDeptName,keyWord);
        lambdaQueryWrapper.in(classIds!=null,SysDept::getId,classIds);
        PageHelper.startPage(pageNum,pageSize);
        List<SysDept> sysDepts = sysDeptMapper.selectList(lambdaQueryWrapper);
        PageInfo<SysDept> pageInfo=new PageInfo<>(sysDepts);
        return pageInfo;
    }

    @Override
    public List<String> GetKeyWord(String keyWord) {
        List<String> strings = sysDeptMapper.selectDeptsByNameLike(keyWord);
        return strings;
    }

    private List<SysDeptVo> buildDepts(List<SysDept> menus) {

        List<SysDeptVo> sysDeptVoList = new LinkedList<SysDeptVo>();
        for (SysDept sysDept : menus) {
            SysDeptVo sysDeptVo = new SysDeptVo();
            sysDeptVo.setDeptLevel(sysDept.getDeptLevel());
            sysDeptVo.setDeptName(sysDept.getDeptName());
            sysDeptVo.setId(sysDept.getId());
            sysDeptVo.setStatus(sysDept.getStatus());
            sysDeptVo.setParentId(sysDept.getParentId());
            sysDeptVo.setDescription(sysDept.getDescription());
            Date createTime = sysDept.getCreateTime();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = df.format(createTime);
            sysDeptVo.setCreateTime(format);
            List<SysDept> children = sysDept.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysDeptVo.setChildren(buildDepts(children));
            }
            sysDeptVoList.add(sysDeptVo);
        }
        return  sysDeptVoList;
    }
}
